package ${groupId}.config.system;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.task.TaskExecutionProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

@ConditionalOnClass(ThreadPoolTaskExecutor.class)
@Configuration
@EnableConfigurationProperties(TaskExecutionProperties.class)
public class ThreadPoolTaskConfig {

	@Autowired
	private TaskExecutionProperties taskExecutionProperties;
	
	@Bean
	public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
		
		TaskExecutionProperties.Pool pool = this.taskExecutionProperties.getPool();
		
		ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
		//核心线程数
		threadPoolTaskExecutor.setCorePoolSize(pool.getCoreSize());
		//最大线程数
		threadPoolTaskExecutor.setMaxPoolSize(pool.getMaxSize());
		//队列最大长度
		threadPoolTaskExecutor.setQueueCapacity(pool.getQueueCapacity());
		//线程池维护线程所允许的空闲时间
		threadPoolTaskExecutor.setKeepAliveSeconds((int)pool.getKeepAlive().getSeconds());
		//线程池对拒绝任务(无线程可用)的处理策略
		threadPoolTaskExecutor.setRejectedExecutionHandler(new java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy());
	    return threadPoolTaskExecutor;
	}
}
